package com.lauor.smpdb.pool;

import java.sql.*;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * @function:数据库连接代理对象
 */
public class SmpConnectionProxy implements Connection {

    private Connection delegate;//代理对象委托者

    private long lastActiveTime;

    private boolean closed;//是否关闭

    private SmpDbPool smpDbPool;//所在连接池

    private boolean isAutoCommit;

    private boolean isCommitStateDirty;

    SmpConnectionProxy(Connection delegate, SmpDbPool dbPool, boolean autoCommit) {
        this.delegate = delegate;
        this.smpDbPool = dbPool;
        this.isAutoCommit = autoCommit;
    }

    public SmpConnectionProxy borrowConnection(){
        this.closed = false;
        this.lastActiveTime = System.currentTimeMillis();
        return this;
    }

    public boolean isValid() throws SQLException {
        if (System.currentTimeMillis() - this.lastActiveTime < this.smpDbPool.getConfig().getKeepAliveTimeMillis()) return true;

        long validationTimeout = this.smpDbPool.getConfig().getValidationTimeoutMillis();
        this.delegate.setNetworkTimeout(this.smpDbPool.getNetTimeoutExecutor(), (int) validationTimeout);
        int validationSeconds = (int) Math.max(1000L, validationTimeout) / 1000;

        return this.delegate.isValid(validationSeconds);
    }

    void destroy() throws SQLException {
        this.closed = true;
        this.delegate.close();
    }

    void markCommitStateDirty() throws SQLException {
        if ( !this.isAutoCommit ) {
            this.isCommitStateDirty = true;
        }
    }

    public void close() throws SQLException {
        if (this.closed) return;

        this.closed = true;
        //回滚掉未提交的脏statement
        if (this.isCommitStateDirty && !this.isAutoCommit){
            this.delegate.rollback();
        }
        this.clearWarnings();
        this.smpDbPool.releaseConnection(this);
    }

    public boolean isClosed() throws SQLException {
        return this.closed;
    }

    public Connection getDelegate() {
        return delegate;
    }

    public void setDelegate(Connection delegate) {
        this.delegate = delegate;
    }

    public long getLastActiveTime() {
        return lastActiveTime;
    }

    public void setLastActiveTime(long lastActiveTime) {
        this.lastActiveTime = lastActiveTime;
    }

    public Statement createStatement() throws SQLException {
        return this.delegate.createStatement();
    }

    public PreparedStatement prepareStatement(String sql) throws SQLException {
        return this.delegate.prepareStatement(sql);
    }

    public CallableStatement prepareCall(String sql) throws SQLException {
        return this.delegate.prepareCall(sql);
    }

    public String nativeSQL(String sql) throws SQLException {
        return this.delegate.nativeSQL(sql);
    }

    public void setAutoCommit(boolean autoCommit) throws SQLException {
        this.delegate.setAutoCommit(autoCommit);
        this.isAutoCommit = autoCommit;
    }

    public boolean getAutoCommit() throws SQLException {
        return this.delegate.getAutoCommit();
    }

    public void commit() throws SQLException {
        this.isCommitStateDirty = false;
        this.delegate.commit();
    }

    public void rollback() throws SQLException {
        this.isCommitStateDirty = false;
        this.delegate.rollback();
    }

    public DatabaseMetaData getMetaData() throws SQLException {
        this.markCommitStateDirty();
        return this.delegate.getMetaData();
    }

    public void setReadOnly(boolean readOnly) throws SQLException {
        this.isCommitStateDirty = false;
        this.delegate.setReadOnly(readOnly);
    }

    public boolean isReadOnly() throws SQLException {
        return this.delegate.isReadOnly();
    }

    public void setCatalog(String catalog) throws SQLException {
        this.delegate.setCatalog(catalog);
    }

    public String getCatalog() throws SQLException {
        return this.delegate.getCatalog();
    }

    public void setTransactionIsolation(int level) throws SQLException {
        this.delegate.setTransactionIsolation(level);
    }

    public int getTransactionIsolation() throws SQLException {
        return this.delegate.getTransactionIsolation();
    }

    public SQLWarning getWarnings() throws SQLException {
        return this.delegate.getWarnings();
    }

    public void clearWarnings() throws SQLException {
        this.delegate.clearWarnings();
    }

    public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
        return this.delegate.createStatement(resultSetType, resultSetConcurrency);
    }

    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        return this.delegate.prepareStatement(sql, resultSetType, resultSetConcurrency);
    }

    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        return this.delegate.prepareCall(sql, resultSetType, resultSetConcurrency);
    }

    public Map<String, Class<?>> getTypeMap() throws SQLException {
        return this.delegate.getTypeMap();
    }

    public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
        this.delegate.setTypeMap(map);
    }

    public void setHoldability(int holdability) throws SQLException {
        this.delegate.setHoldability(holdability);
    }

    public int getHoldability() throws SQLException {
        return this.delegate.getHoldability();
    }

    public Savepoint setSavepoint() throws SQLException {
        return this.delegate.setSavepoint();
    }

    public Savepoint setSavepoint(String name) throws SQLException {
        return this.delegate.setSavepoint(name);
    }

    public void rollback(Savepoint savepoint) throws SQLException {
        this.isCommitStateDirty = false;
        this.delegate.rollback(savepoint);
    }

    public void releaseSavepoint(Savepoint savepoint) throws SQLException {
        this.delegate.releaseSavepoint(savepoint);
    }

    public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return this.delegate.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability);
    }

    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return this.delegate.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
    }

    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return this.delegate.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
    }

    public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
        return this.delegate.prepareStatement(sql, autoGeneratedKeys);
    }

    public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
        return this.delegate.prepareStatement(sql, columnIndexes);
    }

    public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
        return this.delegate.prepareStatement(sql, columnNames);
    }

    public Clob createClob() throws SQLException {
        return this.delegate.createClob();
    }

    public Blob createBlob() throws SQLException {
        return this.delegate.createBlob();
    }

    public NClob createNClob() throws SQLException {
        return this.delegate.createNClob();
    }

    public SQLXML createSQLXML() throws SQLException {
        return this.delegate.createSQLXML();
    }

    public boolean isValid(int timeout) throws SQLException {
        return this.delegate.isValid(timeout);
    }

    public void setClientInfo(String name, String value) throws SQLClientInfoException {
        this.delegate.setClientInfo(name, value);
    }

    public void setClientInfo(Properties properties) throws SQLClientInfoException {
        this.delegate.setClientInfo(properties);
    }

    public String getClientInfo(String name) throws SQLException {
        return this.delegate.getClientInfo(name);
    }

    public Properties getClientInfo() throws SQLException {
        return this.delegate.getClientInfo();
    }

    public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
        return this.delegate.createArrayOf(typeName, elements);
    }

    public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
        return this.delegate.createStruct(typeName, attributes);
    }

    public void setSchema(String schema) throws SQLException {
        this.delegate.setSchema(schema);
    }

    public String getSchema() throws SQLException {
        return this.delegate.getSchema();
    }

    public void abort(Executor executor) throws SQLException {
        this.delegate.abort(executor);
    }

    public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
        this.delegate.setNetworkTimeout(executor, milliseconds);
    }

    public int getNetworkTimeout() throws SQLException {
        return this.delegate.getNetworkTimeout();
    }

    public <T> T unwrap(Class<T> iface) throws SQLException {
        return this.delegate.unwrap(iface);
    }

    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return this.delegate.isWrapperFor(iface);
    }
}
